package com.mojo.concurrent.concurrent_08_collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class CopyOnWriteArrayListDemo01 {
    public static void main(String[] args) {
        failSafe();
        failFast();
    }

    private static void failSafe() {
        CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        Iterator<Integer> iterator = list.iterator();
        int n = 0;
        while (iterator.hasNext()) {
            if (n == 2) {
                list.remove(n);
                list.add(11);
            } else {
                System.out.println("next>>>" + iterator.next());
            }
            n++;

        }
    }

    private static void failFast() {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        Iterator<Integer> iterator = list.iterator();
        int n = 0;
        while (iterator.hasNext()) {
            if (n == 2) {
                //数据结构发生变化
                list.remove(n);
                list.add(11);
            } else {
                //lte
                System.out.println("next>>>" + iterator.next());
            }
            n++;

        }
    }
}
